package com.example.scene;

import org.andengine.engine.camera.Camera;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.entity.modifier.AlphaModifier;
import org.andengine.entity.modifier.LoopEntityModifier;
import org.andengine.entity.modifier.MoveXModifier;
import org.andengine.entity.modifier.MoveYModifier;
import org.andengine.entity.modifier.ParallelEntityModifier;
import org.andengine.entity.modifier.RotationModifier;
import org.andengine.entity.modifier.ScaleModifier;
import org.andengine.entity.modifier.SequenceEntityModifier;
import org.andengine.entity.primitive.Line;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.menu.MenuScene;
import org.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener;
import org.andengine.entity.scene.menu.item.IMenuItem;
import org.andengine.entity.sprite.AnimatedSprite;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.sprite.TiledSprite;
import org.andengine.extension.physics.box2d.PhysicsConnector;
import org.andengine.extension.physics.box2d.PhysicsFactory;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.atlas.bitmap.BuildableBitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource;
import org.andengine.opengl.texture.atlas.buildable.builder.BlackPawnTextureAtlasBuilder;
import org.andengine.opengl.texture.atlas.buildable.builder.ITextureAtlasBuilder.TextureAtlasBuilderException;
import org.andengine.opengl.texture.region.ITiledTextureRegion;
import org.andengine.opengl.util.GLState;
import org.andengine.util.debug.Debug;

import ultility.dataString;

import android.content.SharedPreferences;
import android.hardware.SensorManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Toast;

import checkNetwork.network;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.example.base.BaseScene;
import com.example.fruitpool.Point;
import com.example.manager.ResourcesManager;
import com.example.manager.SceneManager;
import com.example.manager.SceneManager.SceneType;

public class MainMenuScene extends BaseScene implements
		IOnMenuItemClickListener,IOnSceneTouchListener {
	private MenuScene menuChildScene;
	private final int MENU_PLAY = 0;
	private final int MENU_OPTIONS = 1;

	BuildableBitmapTextureAtlas menuTextureAtlas;
	ITiledTextureRegion aa_region ;
	private SharedPreferences audioOptions;
	private SharedPreferences.Editor audioEditor;

	@Override
	public void createScene() {
		audioOptions = activity.getSharedPreferences("audio", activity.MODE_PRIVATE);
		audioEditor = audioOptions.edit();
		resourcesManager.playMusic();
		createBackground();
		createMenuChildScene();
		ResourcesManager.prepareManager(engine, activity, camera, vbom);
		//createMusic();
		this.setOnSceneTouchListener(this);
		
		boolean b = network.chkStatus();  
		if(b==true){
			Log.d("pos1", "co");
		}else{ 
			Log.d("pos1", "ko"); 
		} 
	}

	@Override
	public void onBackKeyPressed() {
		// TODO Auto-generated method stub
		activity.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				activity.showDialog(9);
			}
		});
	}

	@Override
	public SceneType getSceneType() {
		// TODO Auto-generated method stub
		return SceneType.SCENE_MENU;
	}

	@Override
	public void disposeScene() {
		// TODO Auto-generated method stub

	}
	private void createMusic()
	{
		resourcesManager.musicGame.play();
	}
	private void createBackground() {
		attachChild(new Sprite(0, 0, resourcesManager.menu_background_region,
				vbom) {
			@Override
			protected void preDraw(GLState pGLState, Camera pCamera) {
				super.preDraw(pGLState, pCamera);
				pGLState.enableDither();
			}
		});
		
	}

	private void createMenuChildScene() {
		/*menuChildScene = new MenuScene(camera);
		menuChildScene.setPosition(0, 0);

		final IMenuItem playMenuItem = new ScaleMenuItemDecorator(
				new SpriteMenuItem(MENU_PLAY, resourcesManager.newgame_region,
						vbom), 1.2f, 1);
		final IMenuItem optionsMenuItem = new ScaleMenuItemDecorator(
				new SpriteMenuItem(MENU_OPTIONS,
						resourcesManager.highscore_region, vbom), 1.2f, 1);
	
		menuChildScene.addMenuItem(playMenuItem);
		menuChildScene.addMenuItem(optionsMenuItem);

		menuChildScene.buildAnimations();
		menuChildScene.setBackgroundEnabled(false);

		playMenuItem.setPosition(playMenuItem.getX(), playMenuItem.getY() + 10);
		optionsMenuItem.setPosition(optionsMenuItem.getX(),
				optionsMenuItem.getY() + 110);

		menuChildScene.setOnMenuItemClickListener(this);

		setChildScene(menuChildScene);*/
		loadImageMenu();
	}
	Sprite newgame,highscore,timemode,setting,login,help;
	public void loadImageMenu() {
		float rateW = 1;//resourcesManager.wRate;
		float rateH = 1;///resourcesManager.hRate;
		
		int widthText = (activity.CAMERA_WIDTH-60-75)/4;
		int w = (int) (rateW*120);
		int h = (int) (rateW*120);
		
		Log.d("rate","w: "+rateW+",h:"+rateH); 
		PhysicsWorld mPhysicsWorld = new PhysicsWorld(new Vector2(0,SensorManager.GRAVITY_EARTH), true);
		final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1f,0.5f, 0.5f);
		final Rectangle bottom = new Rectangle(0, rateH*180, activity.CAMERA_WIDTH, 1, vbom);	
		bottom.setAlpha(0); 
		final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(1f,0.5f, 0.5f);
		PhysicsFactory.createBoxBody(mPhysicsWorld, bottom,BodyType.StaticBody, wallFixtureDef);
		
		this.attachChild(bottom);  
		this.registerUpdateHandler(mPhysicsWorld);
		
		Sprite backbar = new Sprite(0, -activity.CAMERA_HEIGHT, resourcesManager.backbar_region, vbom);
		backbar.setAlpha(0.6f);
		backbar.registerEntityModifier(new MoveYModifier(2.5f, backbar.getY(), 0));
		this.attachChild(backbar); 
		
		Sprite text = new Sprite(rateW*150, rateH*-130, rateW*250, rateH*120, resourcesManager.text_region, vbom);
		final Body body = PhysicsFactory.createBoxBody(mPhysicsWorld,text, BodyType.DynamicBody, objectFixtureDef);
		this.attachChild(text); 
		mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(text,body, true, true)); 
		 
		final Sprite ninja = new Sprite(rateW*activity.CAMERA_WIDTH/2, -110,rateW*160,rateH*90, resourcesManager.ninja_region, vbom);
		final Body body1 = PhysicsFactory.createBoxBody(mPhysicsWorld,ninja, BodyType.DynamicBody, objectFixtureDef);
		this.attachChild(ninja); 
		mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(ninja,body1, true, true));
		
		Sprite oldman = new Sprite(rateW*5, rateH*10, rateW*160, rateH*250, resourcesManager.oldman_region, vbom);
		oldman.registerEntityModifier(new AlphaModifier(5f, 0f, 1f));
		this.attachChild(oldman);
		
		
		Sprite slice = new Sprite(rateW*0, rateW*200,rateW*170,rateH*130,resourcesManager.slice_region, vbom);
		//slice.setSize(rateWidth*287,rateHeight* 180);
		slice.registerEntityModifier(new MoveXModifier(2, slice.getX(), 40));
	
		timemode = new Sprite(rateW*(30+3*widthText+70),rateW*60,w,h,resourcesManager.timemode_region, vbom);
		timemode.setAlpha(0.5f);
		timemode.registerEntityModifier(new LoopEntityModifier(new RotationModifier(15, 0,360)));
		 
		newgame= new Sprite(rateW*580,rateW*180,w,h, resourcesManager.newgame_region, vbom);
		newgame.setAlpha(0.5f);
		newgame.registerEntityModifier(new LoopEntityModifier(new RotationModifier(15, 0,360)));
		
	
		highscore= new Sprite(rateW*30,rateH*320,rateW*150,rateH*150, resourcesManager.highscore_region, vbom);
		highscore.setAlpha(0.5f);
		highscore.registerEntityModifier(new LoopEntityModifier(new RotationModifier(15, 0,360)));
		   
		setting= new Sprite(rateW*(30+widthText+30),rateH*activity.CAMERA_HEIGHT/2-20,rateW*150,rateH*150, resourcesManager.setting_region, vbom);
		setting.setAlpha(0.5f); 
		setting.registerEntityModifier(new LoopEntityModifier(new RotationModifier(15, 0,360)));
		
		login= new Sprite(rateW*(30+2*widthText+60),rateH*activity.CAMERA_HEIGHT/2-10,rateW*150,rateH*150, resourcesManager.login_region, vbom);
		login.setAlpha(0.5f);
		login.registerEntityModifier(new LoopEntityModifier(new RotationModifier(15, 0,360)));
		 
		help= new Sprite(rateW*(30+3*widthText+76),rateH*320,rateW*150,rateH*150, resourcesManager.help_region, vbom);
		help.setAlpha(0.5f);
		help.registerEntityModifier(new LoopEntityModifier(new RotationModifier(15, 0,360)));
		
		 BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("menu/");
		 BuildableBitmapTextureAtlas NTextureAtlas = new BuildableBitmapTextureAtlas(activity.getTextureManager(), 1024, 1024, TextureOptions.DEFAULT);
		 ITiledTextureRegion N_region = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(NTextureAtlas, activity.getAssets(), "n.png", 5, 5);
		 BuildableBitmapTextureAtlas HTextureAtlas = new BuildableBitmapTextureAtlas(activity.getTextureManager(), 1024, 1024, TextureOptions.DEFAULT);
		 ITiledTextureRegion H_region = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(HTextureAtlas, activity.getAssets(), "h.png", 6, 4);
		 BuildableBitmapTextureAtlas LTextureAtlas = new BuildableBitmapTextureAtlas(activity.getTextureManager(), 1024, 1024, TextureOptions.DEFAULT);
		 ITiledTextureRegion L_region = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(LTextureAtlas, activity.getAssets(), "l.png", 5, 5);
		try 
		{
		    NTextureAtlas.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0, 0, 0));
		    NTextureAtlas.load();
		    HTextureAtlas.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0, 0, 0));
		    HTextureAtlas.load();
		    LTextureAtlas.build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(0, 0, 0));
		    LTextureAtlas.load();
		} 
		catch (final TextureAtlasBuilderException e)
		{
		        Debug.e(e);
		}
		
		int widthNew = 100;
		int heightNew= 100;
		
		AnimatedSprite textN= new AnimatedSprite(newgame.getX()+newgame.getWidth()/2-widthNew/2, 
				newgame.getY()+newgame.getHeight()/2-heightNew/2, widthNew,heightNew,
				N_region, resourcesManager.vbom);
		textN.animate(100, true);
		textN.registerEntityModifier(new LoopEntityModifier(new RotationModifier(5, 0, 360)));
		this.attachChild(textN);
		
		int widthHigh = 80;
		int heightHigh= 80;
		AnimatedSprite textH= new AnimatedSprite(highscore.getX()+highscore.getWidth()/2-widthHigh/2, 
				highscore.getY()+highscore.getHeight()/2-heightHigh/2, widthHigh,heightHigh,
				H_region, resourcesManager.vbom);
		textH.animate(100, true);
		textH.registerEntityModifier(new LoopEntityModifier(new RotationModifier(5, 0, 360)));
		this.attachChild(textH);
		
		AnimatedSprite textHelp= new AnimatedSprite(help.getX()+help.getWidth()/2-widthHigh/2, 
				help.getY()+help.getHeight()/2-heightHigh/2, widthHigh,heightHigh,
				H_region, resourcesManager.vbom);
		textHelp.animate(100, true);
		textHelp.registerEntityModifier(new LoopEntityModifier(new RotationModifier(5, 0, 360)));
		this.attachChild(textHelp);
		
		AnimatedSprite textLogin= new AnimatedSprite(login.getX()+login.getWidth()/2-widthHigh/2, 
				login.getY()+login.getHeight()/2-heightHigh/2, widthHigh,heightHigh,
				L_region, resourcesManager.vbom);
		textLogin.animate(100, true);
		textLogin.registerEntityModifier(new LoopEntityModifier(new RotationModifier(5, 0, 360)));
		this.attachChild(textLogin);

		
		this.attachChild(timemode);
		this.attachChild(newgame);
		this.attachChild(highscore);
		this.attachChild(setting);
		this.attachChild(login);
		this.attachChild(help);
		this.attachChild(slice);

		//	TiledSprite music = new TiledSprite(pX, pY, pTiledTextureRegion, pTiledSpriteVertexBufferObject)
			if (audioOptions.getBoolean("musicOn", true)) {
				index = 0;
			}else{ 
				index = 1;
			}
			if (audioOptions.getBoolean("effectsOn", true)) {
				indexS = 0;
			}else{ 
				indexS = 1;
			}
			music = new TiledSprite(rateW*665, 10,rateW*50,rateH*40, resourcesManager.mTiledTextureRegionMusic, vbom)
			{
				@Override
				public boolean onAreaTouched(final TouchEvent pAreaTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
					switch(pAreaTouchEvent.getAction()) {
					case TouchEvent.ACTION_DOWN:
						break; 
					case TouchEvent.ACTION_UP:
						if (audioOptions.getBoolean("musicOn", true)) {
							audioEditor.putBoolean("musicOn", false);
							if (resourcesManager.musicGame.isPlaying()) resourcesManager.musicGame.pause();
							AlphaModifier mod = new AlphaModifier(0.3f, 1, 0);
							AlphaModifier mod1 = new AlphaModifier(0.01f, 0, 1);
							this.registerEntityModifier(new SequenceEntityModifier(mod,mod1));
							index = 1;
	this.registerUpdateHandler(new TimerHandler(0.3f, new ITimerCallback() {
								
								@Override
								public void onTimePassed(TimerHandler pTimerHandler) {
									music.setCurrentTileIndex(index);								
								}
							}));
								 
						} else {
							audioEditor.putBoolean("musicOn", true);
							if(!resourcesManager.musicGame.isPlaying()){
								resourcesManager.musicGame.play();
							}else{
							resourcesManager.musicGame.resume();
							}
							AlphaModifier mod = new AlphaModifier(0.3f, 1, 0);
							AlphaModifier mod1 = new AlphaModifier(0.0001f, 0, 1);
							this.registerEntityModifier(new SequenceEntityModifier(mod,mod1));
							index = 0;
							
							this.registerUpdateHandler(new TimerHandler(0.3f, new ITimerCallback() {
								
								@Override
								public void onTimePassed(TimerHandler pTimerHandler) {
									music.setCurrentTileIndex(index);								
								}
							}));
						} 
						audioEditor.commit();
						
						break;
					} 
					return true;
				}
			};
			music.setCurrentTileIndex(index);
			sound = new TiledSprite(rateW*610, 10,rateW*50,rateH*40, resourcesManager.mTiledTextureRegionSound, vbom)
			{
				@Override
				public boolean onAreaTouched(final TouchEvent pAreaTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
					switch(pAreaTouchEvent.getAction()) {
					case TouchEvent.ACTION_DOWN:
						break;
					case TouchEvent.ACTION_UP:
						if (audioOptions.getBoolean("effectsOn", true)) {
							audioEditor.putBoolean("effectsOn", false);
							AlphaModifier mod = new AlphaModifier(0.3f, 1, 0);
							AlphaModifier mod1 = new AlphaModifier(0.0001f, 0, 1);
							this.registerEntityModifier(new SequenceEntityModifier(mod,mod1));
							indexS = 1;
							this.registerEntityModifier(mod);
	this.registerUpdateHandler(new TimerHandler(0.3f, new ITimerCallback() {
								
								@Override
								public void onTimePassed(TimerHandler pTimerHandler) {
									sound.setCurrentTileIndex(indexS);										
								}
							}));						
						} else {
							audioEditor.putBoolean("effectsOn", true);
							AlphaModifier mod = new AlphaModifier(0.3f, 1, 0);
							AlphaModifier mod1 = new AlphaModifier(0.0001f, 0, 1);
							this.registerEntityModifier(new SequenceEntityModifier(mod,mod1));
							indexS = 0;
	this.registerUpdateHandler(new TimerHandler(0.3f, new ITimerCallback() {
								
								@Override
								public void onTimePassed(TimerHandler pTimerHandler) {
									sound.setCurrentTileIndex(indexS);								
								}
							}));
						} 
						audioEditor.commit();
			
						break;
					}
					return true;
				}
			};
			sound.setCurrentTileIndex(indexS);
			
			//final Sprite x = new Sprite(rateW*520, -50,rateW*140,rateH*100, resourcesManager.mTextureRegionX, vbom);
			//final Sprite x1 = new Sprite(rateW*520, -50,rateW*140,rateH*100, resourcesManager.mTextureRegionX, vbom);
			//final Sprite x2 = new Sprite(rateW*520, -50,rateW*140,rateH*100, resourcesManager.mTextureRegionX, vbom);
			this.attachChild(music);
			this.attachChild(sound);
			this.registerTouchArea(music); 
			this.registerTouchArea(sound);
			this.setTouchAreaBindingOnActionDownEnabled(true);
		}
		int index = 0;
		int indexS = 0;
		TiledSprite sound;
		TiledSprite music;
	int x1Convert, y1Convert, x2Convert, y2Convert;
	public void convertTouch(int x1, int y1, int x2, int y2)
	{
		x1Convert = (int) (x1*resourcesManager.wRate);
		y1Convert = (int) (y1*resourcesManager.hRate);
		x2Convert = (int) (x2*resourcesManager.wRate);
		y2Convert = (int) (y2*resourcesManager.hRate);
		
		Log.d("inconvert", x1+"->"+x1Convert+":"+y1+"->"+y1Convert);
	}
	Point currPoint=new Point(); 
	Point prevPoint=new Point();
	Line line;

	public boolean onMenuItemClicked(MenuScene pMenuScene, IMenuItem pMenuItem,
			float pMenuItemLocalX, float pMenuItemLocalY) {
		switch (pMenuItem.getID()) {
		case MENU_PLAY:
			SceneManager.getInstance().loadGameScene(engine);
			return true;
		case MENU_OPTIONS:
			SceneManager.getInstance().loadHighScoresScene(engine);
			return true;
		default:
			return false;
		}
	}
	boolean slash=true;
	@Override
	public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
		Log.d("onSceneTouchEvent","onSceneTouchEvent");
		synchronized (this) {
			switch (pSceneTouchEvent.getAction()) {
			case MotionEvent.ACTION_DOWN:
				currPoint=new Point();
				currPoint.x=(int) pSceneTouchEvent.getMotionEvent().getX();
				currPoint.y=(int) pSceneTouchEvent.getMotionEvent().getY();
				break;
			case MotionEvent.ACTION_UP:
				this.detachChild(line);
				slash=true;
				break; 
			case MotionEvent.ACTION_MOVE:
				prevPoint=new Point();
				prevPoint.x = (int) pSceneTouchEvent.getMotionEvent().getX();
				prevPoint.y = (int) pSceneTouchEvent.getMotionEvent().getY();
				Log.d("prevPoint",prevPoint.x+":"+prevPoint.y);
				convertTouch(prevPoint.x, prevPoint.y,currPoint.x, currPoint.y);
				line = new Line(x2Convert,y2Convert,x1Convert,y1Convert,vbom);
				Log.d("x2Convert",x2Convert+":"+y2Convert+"-"+x1Convert+":"+y1Convert);
				line.setLineWidth(3);
				line.setAlpha(0);
				this.attachChild(line);
				boolean music = audioOptions.getBoolean("musicOn", true);
				boolean sound = audioOptions.getBoolean("effectsOn", true);
				if(newgame.collidesWith(line))
				{
					if(sound){
					resourcesManager.sliceSound.play();
					}
					resourcesManager.musicGame.pause();
					SceneManager.getInstance().loadGameScene(engine);		
				}
				
				if(highscore.collidesWith(line))
				{
					if(slash){
						if(sound)	resourcesManager.sliceSound.play();
						slash=false;
					}
					if(music)
					resourcesManager.playMusic();
					SceneManager.getInstance().loadHighScoresScene(engine);
				}
				
				if(timemode.collidesWith(line))
				{
					if(slash){
						if(sound)
						resourcesManager.sliceSound.play();
						slash=false;
					}
					if(music)
					resourcesManager.playMusic();
					SceneManager.getInstance().loadTimerMode(engine);
				}
				
				if(setting.collidesWith(line))
				{
					if(slash){
						if(sound)
						resourcesManager.sliceSound.play();
						slash=false;
						activity.runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								// TODO Auto-generated method stub
								if (network.chkStatus()) // << your method from above
								{
										activity.runOnUiThread(new Runnable() {
										
										@Override
										public void run() {
											// TODO Auto-generated method stub
											activity.message="Network available";
											activity.showDialog(4);
										}
									});
								}
								else
								{
									activity.runOnUiThread(new Runnable() {
										
										@Override
										public void run() {
											// TODO Auto-generated method stub
											activity.message="No network available";
											activity.showDialog(4);
										}
									});
								}
							}
						});
						
						
					}
					if(music)
					resourcesManager.playMusic();
				}
				
				if(login.collidesWith(line))
				{
					if(slash){
						if(sound)
						resourcesManager.sliceSound.play();
						slash=false;
						activity.runOnUiThread(new Runnable() {			
							@Override
							public void run() {
								// TODO Auto-generated method stub
								activity.showDialog(3);
							} 
						});	
					}
					if(music)
					resourcesManager.playMusic();
				}
				
				if(help.collidesWith(line))
				{
					if(slash){
						if(sound)
						resourcesManager.sliceSound.play();
						slash=false;
					}
					if(music)
					resourcesManager.playMusic();
				}
				currPoint = prevPoint;
				break;
			}
			return true;
		}
	}
}
